package com.woniuxy.charin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.charin.enumeration.EventStatus;
import com.woniuxy.charin.enumeration.EventType;
import com.woniuxy.charin.model.entity.Event;
import com.woniuxy.charin.model.entity.EventDispose;
import com.woniuxy.charin.model.request.EventRequest;
import com.woniuxy.charin.model.vo.EventDetailVo;
import com.woniuxy.charin.service.ChargingPileService;
import com.woniuxy.charin.service.EventDisposeService;
import com.woniuxy.charin.service.EventService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(tags = "隐患故障模块")
@RestController
@RequestMapping("/event")
public class EventController {
    @Autowired
    EventService eventService;
    @Autowired
    EventDisposeService eventDisposeService;
    @Autowired
    ChargingPileService chargingPileService;

    //通用相关操作====================================================
    @ApiOperation("删除事件")
    @DeleteMapping("/deleteEvent/{eventIds}")
    public ResponseEntity<?> deleteRisk(@PathVariable Long... eventIds) {
        for (Long eventId : eventIds) {
            //删除事件记录
            eventService.removeById(eventId);
            //删除处理记录（与该事件相关的全部处理记录）
            LambdaQueryWrapper<EventDispose> eq = Wrappers.lambdaQuery(EventDispose.class).eq(EventDispose::getEventId, eventId);
            List<EventDispose> list = eventDisposeService.list(eq);
            for (EventDispose eventDispose : list) {
                eventDisposeService.removeById(eventDispose.getId());
            }
        }
        return ResponseEntity.ok("删除隐患记录成功");
    }

    @ApiOperation("撤销事件")
    @GetMapping("/retracteEvent/{eventIds}")
    public ResponseEntity<?> retracteRisk(@RequestParam String returnCause,
                                          @PathVariable Long... eventIds) {
        eventService.retracteRisk(eventIds, returnCause);
        return ResponseEntity.ok("撤销隐患记录成功");
    }

    @ApiOperation("根据事件id获取事件详情")
    @GetMapping("/getEventDetail/{riskId}")
    public ResponseEntity<?> getRiskDetail(@PathVariable Integer riskId) {
        EventDetailVo detail = eventService.getRiskDetail(riskId);
        return ResponseEntity.ok(detail);
    }
    //通用相关操作====================================================
    //隐患相关操作====================================================
    @ApiOperation("分页查找隐患记录")
    @PostMapping("/pageRisk")
    public ResponseEntity<?> pageRisk(@RequestBody Map<String, Object> params) {
        //获取页码和页面大小
        Integer pageNum = (Integer) params.get("pageNum");
        Integer pageSize = (Integer) params.get("pageSize");
        List<Integer> chargingPileIds = (List<Integer>) params.get("chargingPileIds");
        String startDateStr = (String) params.get("startDate");
        String endDateStr = (String) params.get("endDate");
        Date startDate = startDateStr != null ? strToData(startDateStr) : null;
        Date endDate = endDateStr != null ? strToData(endDateStr) : null;
        //调用服务层方法分页查找
        Page<EventDetailVo> page = eventService.pageRisk(pageNum, pageSize, chargingPileIds, startDate, endDate);
        //返回查找结果
        return ResponseEntity.ok(page);
    }

    @ApiOperation("修改隐患")
    @PostMapping("/editRisk")
    public ResponseEntity<?> editRisk(@RequestBody EventRequest request) {
        eventService.editRisk(request);
        //返回查找结果
        return ResponseEntity.ok("修改隐患记录成功");
    }

    @ApiOperation("新增隐患")
    @PostMapping("/addRisk")
    public ResponseEntity<?> addRisk(@RequestBody EventRequest request) {
        //获取Event对象相关信息
        Event event = new Event();
        event.setEventType(EventType.RISK.getKey());
        event.setCurrentStatus(EventStatus.PENDING.getKey());
        BeanUtils.copyProperties(request, event);
        eventService.addRisk(event);
        return ResponseEntity.ok("新增隐患记录成功");
    }

    @ApiOperation("统计隐患待指派数")
    @GetMapping("/statisticsRisk")
    public ResponseEntity<?> statisticsRisk() {
        Integer count = eventService.count(Wrappers.lambdaQuery(Event.class)
                .eq(Event::getEventType, EventType.RISK.getKey())
                .eq(Event::getCurrentStatus, EventStatus.PENDING.getKey()));
        return ResponseEntity.ok(count);
    }
    //隐患相关操作====================================================
    //故障相关操作====================================================
    @ApiOperation("分页查找故障记录")
    @PostMapping("/pageFault")
    public ResponseEntity<?> pageFault(@RequestBody Map<String, Object> params) {
        //获取页码和页面大小
        Integer pageNum = (Integer) params.get("pageNum");
        Integer pageSize = (Integer) params.get("pageSize");
        List<Integer> chargingPileIds = (List<Integer>) params.get("chargingPileIds");
        String startDateStr = (String) params.get("startDate");
        String endDateStr = (String) params.get("endDate");
        Date startDate = startDateStr != null ? strToData(startDateStr) : null;
        Date endDate = endDateStr != null ? strToData(endDateStr) : null;
        //调用服务层方法分页查找
        Page<EventDetailVo> page = eventService.pageFault(pageNum, pageSize, chargingPileIds, startDate, endDate);
        //返回查找结果
        return ResponseEntity.ok(page);
    }

    @ApiOperation("修改故障")
    @PostMapping("/editFault")
    public ResponseEntity<?> editFault(@RequestBody EventRequest request) {
        eventService.editFault(request);
        //返回查找结果
        return ResponseEntity.ok("修改故障记录成功");
    }

    @ApiOperation("新增故障")
    @PostMapping("/addFault")
    public ResponseEntity<?> addFault(@RequestBody EventRequest request) {
        //获取Event对象相关信息
        Event event = new Event();
        event.setEventType(EventType.FAULT.getKey());
        event.setCurrentStatus(EventStatus.PENDING.getKey());
        BeanUtils.copyProperties(request, event);
        eventService.addFault(event);

        //添加故障成功，则将充电桩状态改为故障中（修改充电桩状态）
        chargingPileService.setChargingPileCracked(Math.toIntExact(request.getChargingPileId()));

        return ResponseEntity.ok("新增故障记录成功");
    }

    @ApiOperation("统计故障待指派数")
    @GetMapping("/statisticsFault")
    public ResponseEntity<?> statisticsFault() {
        Integer count = eventService.count(Wrappers.lambdaQuery(Event.class)
                .eq(Event::getEventType, EventType.FAULT.getKey())
                .eq(Event::getCurrentStatus, EventStatus.PENDING.getKey()));
        return ResponseEntity.ok(count);
    }
    //故障相关操作====================================================


    private Date strToData(String dateStr) {
        // 直接解析字符串为Instant
        Instant instant = Instant.parse(dateStr);
        // 将Instant转换为java.util.Date
        Date date = Date.from(instant);
        return date;
    }
}